<?php

class GalleryModel extends Model{
	
	public $definitions = array(
		"tables" => array("gallery","gallery_items")
	);
	
	public $order = "`gallery`.`date`";
	public $order_direction = "DESC";
	
	function __construct(){
		parent::__construct();
	}
	
	function getAll($id=null) {
		
		if ($id) {
			$gallery = $this->findRow("*", array("id"=>$id));
			
			$this->table_index = 1;
			$this->order = "position";
			$this->order_direction = "asc";
			
			$items = $this->find("*", array("gallery_id"=>$id), false);
			$gallery["items"] = array("image"=>array(), "video"=>array());
			foreach ($items as $row) {
				$gallery["items"][$row["type"]][] = $row;
			}
			
			return $gallery;
			
		}else{
			$galleries = $this->find("*",false,false);
			
			$this->table_index = 1;
			$this->order = "id";
			$this->order_direction = "asc";
			
			foreach ($galleries as $k=>&$gallery) {
				if ($getItems) {
					$items = $this->find("*", array("gallery_id"=>$gallery["id"]), false);
					$gallery["cover"] = 0;
					foreach ($items as $k=>$item) {
						if ($item["cover"]) {
							$gallery["cover"] = $k;
							break;
						}
					}
					$gallery["items"] = $items;
				}else{
					$cover = $this->findRow("*", array("gallery_id"=>$gallery["id"], "cover"=>1), false);
					if(!$cover) {
						$cover = $this->findRow("*", array("gallery_id"=>$gallery["id"]), array(0,1));
					}
					$gallery["cover"] = $cover;
					
					$gallery["count"] = $this->findOne("COUNT(`id`)", array("gallery_id"=>$gallery["id"]));
				}
			}
			return $galleries;
		}
	}
	
	function updatePositions($order) {
		if (is_array($order)) {
			foreach ($order as $position=>$id) {
				$this->update(array("position"=>$position), array("id"=>$id), 1);
			}
		}
	}
	
	function getItem($id) {
		$this->table_index = 1;
		$this->order = "id";
		$this->order_direction = "asc";
		return $this->findRow("*", array("id"=>$id), false);
	}
}

?>